import {getcity, addcity, getmyaddress, delcity, upaddress} from '../../assets/js/request.js'
const state = {
    cityAddressArr: JSON.parse(localStorage.getItem('address')) || []
}
const mutations = {
    // 将获取回来的地址列表赋值给state
    GetMyAeddrss(state, list) {
        state.cityAddressArr = list
    },
    // 删除vuex里对应id的地址
    DelCity(state, id) {
        state.cityAddressArr = state.cityAddressArr.filter(item => item.id != id)
        // console.log(state.cityAddressArr)
    },
}
const actions = {
    // 请求获取自己的地址列表
    async getMyAdderss({commit}) {
        let addressArr = await getmyaddress()
        commit("GetMyAeddrss", addressArr)
        // console.log(addressArr)
    },
    // 可以在页面异步的获取自己地址列表的回调
    getMyAdderss2({commit}) {
        return getmyaddress();
    },
    // 添加收货地址
    addCityRequest(context, values) {
        // 提取出要传的参数
        let formdata = {}
        formdata.name = values.username
        formdata.phone = values.userphone
        formdata.area = `${values.city[0]},${values.city[1]},${values.city[2]}`
        formdata.area_name = `${values.cityList[0].cityname}${values.cityList[1].cityname}${values.cityList[2].cityname}`
        formdata.desc = values.address
        // console.log('表单里的数据: ', values , formdata)
        return addcity(formdata)
    },
    // 删除收货地址
    async delCity({commit}, id) {
        // console.log(id)
        await delcity(id)
        .then(res => {
            commit('DelCity', id)
        })
        .catch(err => {

        })
    },
    // 修改收货地址
    upAddress({dispatch}, values) {
        let formdata = {}
        formdata.name = values.username
        formdata.phone = values.userphone
        formdata.area = `${values.city[0]},${values.city[1]},${values.city[2]}`
        formdata.area_name = values.area_name
        formdata.desc = values.address
        formdata.id = values.id
        console.log(formdata)
        return upaddress(formdata)
    }
}
const getters = {
    
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}